﻿using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using DocumentMaking.FluentNext.Dialogs;
using DocumentMaking.FluentNext.ViewModels;

namespace DocumentMaking.FluentNext.Views;

public partial class MainView : UserControl
{
    public MainView()
    {
        InitializeComponent();
        ItemsControl.ItemsSource = new[]
        {
            new PageRecord("帮助", "\uE11B", "Help", "对整个软件的介绍与帮助"),
            new PageRecord("Python脚本工具", "\uEC7A", "Python", "使用Python脚本工具")
        };
    }

    private async void SelectionClick(object? sender, RoutedEventArgs e)
    {
        if(sender is not Control control)return;
        if(control.DataContext is not PageRecord page)return;
        var name = GetType().FullName;
        if(string.IsNullOrEmpty(name))return;
        name = name.Replace("View", "Page").Replace("Main",page.PageTag);
        var type = Type.GetType(name);
        if (type == null)
        {
            var td = this.GetDialog($"{page.PageTag}Page 找不到");
            td.XamlRoot = (Visual)VisualRoot!;
            await td.ShowAsync();
            return;
        }
        try
        {
            Control.Content = (Control)Activator.CreateInstance(type)!;
        }
        catch (Exception exception)
        {
            var td = this.GetDialog(exception);
            td.XamlRoot = (Visual)VisualRoot!;
            await td.ShowAsync();
            return;
        }
        
        ItemsControl.IsVisible = false;
    }

    private void BackClick(object? sender, RoutedEventArgs e)
    {
        ItemsControl.IsVisible = true;
        Control.Content = null;
    }
}